package com.xqls.server.netty;

import com.alibaba.fastjson.JSON;
import com.xqls.dal.model.DeviceSchema;
import com.xqls.server.dto.FluSoketCommonDto;
import com.xqls.server.dto.SoketCommonDto;
import com.xqls.util.ContextUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.ref.Reference;

/**
 * Created by Skeyedu on 2017/3/9.
 */
public class CommonDecoder extends ChannelInboundHandlerAdapter {
    private static final Logger LOG = LoggerFactory
            .getLogger(CommonDecoder.class);



    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
//        ByteBuf fram= (ByteBuf)super.decode(ctx,in);
//
//        in.release();
//        if (fram == null) {
//            return null;
//        }
        SoketCommonDto    commonDto=SoketCommonDto.getDecode(in);
        in.clear();
        if(commonDto==null){
            LOG.error("解析协议异常");
        }
        ReferenceCountUtil.release(in);

        return commonDto;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in=(ByteBuf)msg;
        SoketCommonDto    commonDto=SoketCommonDto.getDecode(in);
        try {
            if(commonDto==null){
                LOG.error("解析协议异常");
            }
            ctx.fireChannelRead(commonDto);
        }catch (Exception e){

        }finally {
            in.discardReadBytes();
            ReferenceCountUtil.release(in);
        }


    }



}
